Attribute VB_Name = "modCOMDllLoader"
'***************************************************************
' (c) Copyright 2000 Matthew J. Curland
'
' This file is from the CD-ROM accompanying the book:
' Advanced Visual Basic 6: Power Techniques for Everyday Programs
'   Author: Matthew Curland
'   Published by: Addison-Wesley, July 2000
'   ISBN: 0-201-70712-8
'   http://www.PowerVB.com
'
' You are entitled to license free distribution of any application
'   that uses this file if you own a copy of the book, or if you
'   have obtained the file from a source approved by the author. You
'   may redistribute this file only with express written permission
'   of the author.
'
' This file depends on:
'   References:
'     VBoostTypes6.olb (VBoost Object Types (6.0))
'     ObjCreate.olb (VBoost: Object Creation and Security) 
'   Files:
'     FunctionDelegator.bas
'   Minimal VBoost conditionals:
'     None
'   Conditional Compilation Values:
'     FUNCTIONDELEGATOR_NOHEAP = 1 (optional)
'
' This file is discussed in Chapter 7.
'***************************************************************
Option Explicit

Private m_fInit As Boolean
Public IID_IClassFactory As IID
Public IID_IUnknown As IID
Private m_FDDllGetClassObject As FunctionDelegator
Private m_pCallDllGetClassObject As ICallDllGetClassObject
Private m_FDDllCanUnloadNow As FunctionDelegator
Private m_pCallDllCanUnloadNow As ICallDllCanUnloadNow

Private Sub Init()
    IID_IClassFactory = IIDFromString(strIID_IClassFactory)
    IID_IUnknown = IIDFromString(strIID_IUnknown)
    Set m_pCallDllGetClassObject = InitDelegator(m_FDDllGetClassObject)
    Set m_pCallDllCanUnloadNow = InitDelegator(m_FDDllCanUnloadNow)
    m_fInit = True
End Sub

Public Function GetDllClassObject(ByVal DllPath As String, CLSID As CLSID, hModDll As hInstance) As IClassFactory
    If Not m_fInit Then Init
    If hModDll = 0 Then
        hModDll = LoadLibraryEx(DllPath, 0, LOAD_WITH_ALTERED_SEARCH_PATH)
        If hModDll = 0 Then
            Err.Raise &H80070000 + Err.LastDllError
        End If
    End If
    m_FDDllGetClassObject.pfn = GetProcAddress(hModDll, "DllGetClassObject")
    If m_FDDllGetClassObject.pfn = 0 Then
        Err.Raise &H80070000 + Err.LastDllError
    End If
    Set GetDllClassObject = m_pCallDllGetClassObject.Call(CLSID, IID_IClassFactory)
End Function

Public Sub TestUnloadDll(hModDll As hInstance)
    If hModDll Then
        If Not m_fInit Then Init
        m_FDDllCanUnloadNow.pfn = GetProcAddress(hModDll, "DllCanUnloadNow")
        If m_FDDllCanUnloadNow.pfn = 0 Then
            Err.Raise &H80070000 + Err.LastDllError
        End If
        If m_pCallDllCanUnloadNow.Call = 0 Then
            FreeLibrary hModDll
            hModDll = 0
        End If
    End If
End Sub
